package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.TemperatureHis;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.TemperatureHisService;
import com.bbzn.device.client.utils.OptionalBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Component
public class EmqTempStrategy implements EmqStrategy {

    @Resource
    private TemperatureHisService temperatureHisService;

    @Autowired
    private DeviceService deviceService;

    // 手表体温信息
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            Double temperature = jsonObject.getDouble("temperature");
            if (!OptionalBean.ofNullable(temperature).isPresent()) {
                return "json解析错误";
            }
            TemperatureHis temperatureHis = new TemperatureHis();
            temperatureHis.setImei(imei);
            temperatureHis.setTemperature(temperature);
            temperatureHis.setCreateTime(new Date());   //new Timestamp(System.currentTimeMillis())
            temperatureHis.setCreatedBy("emq");
            temperatureHisService.insertSelective(temperatureHis);

            Device device = new Device();
            device.setImei(imei);
            device.setTemperate(temperature);
            deviceService.updateByImeiSelective(device);
        } catch (Exception e) {
            return "获取体温失败！";
        }
        return "获取体温成功！";
    }
}
